package db;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

public class HibernateHelper {
	private static final SessionFactory sessionFactory = buildSessionFactory();

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	private static SessionFactory buildSessionFactory() {
		try {
			// Nicht notwendig: .addClass(*.class), da in
			// cfg.xml enthalten!
			return new Configuration().configure("hibernate.cfg.xml")
					.buildSessionFactory();
		} catch (Throwable e) {
			System.err
					.println("Fehler beim Erzeugen der SessionFactory aufgetreten! "
							+ e);
			throw new ExceptionInInitializerError(e);
		}
	}

	public static <T> List<T> listAll(Class<T> klasse) {
		Session session = HibernateHelper.getSessionFactory()
				.getCurrentSession();
		session.beginTransaction();
		@SuppressWarnings("unchecked")
		List<T> result = session.createCriteria(klasse).list();

//		session.getTransaction().commit();
//		session.disconnect();

		return result;
	}

	public static <T> T retrieveObject(Class<T> klasse, Object idValue) {
		Session session = HibernateHelper.getSessionFactory()
				.getCurrentSession();
		session.beginTransaction();

		Criteria c = session.createCriteria(klasse);
		Criterion filter = Restrictions.idEq(idValue);
		c.add(filter);
		T result;
		try {
			result = (T) c.uniqueResult();
//			session.getTransaction().commit();
		} catch (RuntimeException e) {
			throw new RuntimeException(e);
		} finally {
//			session.disconnect();
		}

		return result;
	}

	public static Serializable save(Object object) {

		Session session = HibernateHelper.getSessionFactory()
				.getCurrentSession();
		session.beginTransaction();

		Serializable result = session.save(object);
		session.getTransaction().commit();
//		session.disconnect();

		return result;
	}

	public static void saveOrUpdate(Object object) {
		Session session = HibernateHelper.getSessionFactory()
				.getCurrentSession();
		session.beginTransaction();
		
		session.saveOrUpdate(object);
		session.getTransaction().commit();
		
//		session.disconnect();

	}
	
	public static void delete(Object object) {
		Session session = HibernateHelper.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.delete(object);
		session.getTransaction().commit();
	}

}
